#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
pthread_cond_t cond;
int flag = 0;

void * threadFunction1(void *)
{
    pthread_mutex_lock(&mutex);
    
    while(flag != 0)
    {
        pthread_cond_wait(&cond , &mutex);
    }
    
    printf(" A ->");
    flag = 1;
    pthread_cond_signal(&cond);
    
    while(flag != 2)
    {
        pthread_cond_wait(&cond , &mutex);
    }
    
    printf(" C \n");
    flag = 0;
    pthread_cond_signal(&cond);
    
    pthread_mutex_unlock(&mutex);

    return NULL;
}

void * threadFunction2(void *)
{
    pthread_mutex_lock(&mutex);
    
    while(flag != 1)
    {
        pthread_cond_wait(&cond , &mutex);
    }
    
    printf(" B ->");
    flag = 2;
    pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);
    
    return NULL;
}

int main()
{
    pthread_t pthid1 , pthid2;
    
    pthread_mutex_init(&mutex , NULL);
    pthread_cond_init(&cond , NULL);

    pthread_create(&pthid1 , NULL , threadFunction1 , NULL);
    pthread_create(&pthid2 , NULL , threadFunction2 , NULL);

    pthread_join(pthid1 , NULL);
    pthread_join(pthid2 , NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    sleep(1);
    
    printf("main thread is over ! \n");

    return 0;
}

